package com.feng.test.biji;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.*;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author HuangSuip
 */
public class BiJiP {

    public static void main(String[] args) throws IOException, InterruptedException {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("BIJI").build();
        ExecutorService executorService = new ThreadPoolExecutor(
            10, 100, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        //ExecutorService exec = Executors.newFixedThreadPool(100);
        String url = "http://image.bee-ji.com/";
        OkHttpClient client = new OkHttpClient();

        for (int i = 1; i < 100; i++) {
            Thread.sleep(10);
            executorService.submit(new Biji(url  + i, client, i));
            System.out.println("next");
        }
    }
}

class Biji implements Runnable {

    private String url;
    private OkHttpClient client;
    private int i;

    public Biji(String url, OkHttpClient client, int i) {
        this.url = url;
        this.client = client;
        this.i = i;
    }

    @Override
    public void run() {
        Request request = new Request.Builder().get().url(url).build();
        Response execute = null;
        try {
            execute = client.newCall(request).execute();
            if (execute.code() == 200) {
                ResponseBody body = execute.body();
                byte[] bytes = body.bytes();
                FileOutputStream fos = new FileOutputStream(new File("E:\\biji\\" + i + ".jpg"));
                fos.write(bytes);
                fos.flush();
                fos.close();
                System.out.println("success");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
